package cn.com.manager.controller;

import cn.com.manager.cache.MyCacheManager;
import cn.com.manager.pojo.JsonResult;
import cn.com.manager.pojo.UserSessionManager;
import cn.com.manager.service.SystemService;
import cn.com.manager.utility.ApplicationConstants;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;

/**
 * Created by Administrator on 2016/4/19.
 */
@Controller
@RequestMapping("/session")
public class SessionController {
    @Autowired
    private SystemService systemService;
    @Autowired
    private SessionDAO sessionDAO;

    @RequestMapping
    public String list(Model model){
        Collection<UserSessionManager> userSessions = systemService.getUserSessions();
        model.addAttribute("sessions",userSessions);
        return "session/search";
    }
    @RequestMapping("/logoutUser/{sessionId}")
    @ResponseBody
    public JsonResult logoutUser(@PathVariable("sessionId") String sessionId){
        Session session = sessionDAO.readSession(sessionId);
        session.setAttribute(ApplicationConstants.SESSION_LOGOUT,true);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(0);
        PrincipalCollection principalCollection = (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        jsonResult.setMessage("用户："+(String)principalCollection.getPrimaryPrincipal()+"强制退出成功！");
        return jsonResult;
    }

    @RequestMapping("/{sessionId}")
    @ResponseBody
    public JsonResult checkSession(@PathVariable("sessionId") String sessionId){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(0);
        boolean b = MyCacheManager.checkCacheByName(sessionId);
        jsonResult.setMessage(""+b);
        return jsonResult;
    }
}
